import React from 'react';

namespace Validation {
  export interface StringValidator {
    isAcceptable(s: string): boolean;
  }

  const lettersRegexp = /^[A-Za-z]+$/;
  const numberRegexp = /^[0-9]+$/;

  export class LettersOnlyValidator implements StringValidator {
    isAcceptable(s: string) {
      return lettersRegexp.test(s);
    }
  }

  export class ZipCodeValidator implements StringValidator {
    isAcceptable(s: string) {
      return s.length === 5 && numberRegexp.test(s);
    }
  }
}

export default () => {
  {
    // Some samples to try
    let strings = ["Hello", "98052", "101"];

    // Validators to use
    let validators: { [s: string]: Validation.StringValidator; } = {};
    validators["ZIP code"] = new Validation.ZipCodeValidator();
    validators["Letters only"] = new Validation.LettersOnlyValidator();

    // Show whether each string passed each validator
    for (let s of strings) {
      for (let name in validators) {
        console.log(`"${ s }" - ${ validators[name].isAcceptable(s) ? "matches" : "does not match" } ${ name }`);
      }
    }
  }
  return (
    <div>
      <h1>命名空间</h1>
      <p>1. 功能：有利于组织代码，减少同名类型的命名冲突。我们可以所有验证器相关的类型全部放在 Validation 的命名空间里。可以直接使用 Validation.LettersOnlyValidator。</p>
      <p>2. 命名空间可以将类型分离到多个文件有利于维护。</p>
      <p>3. 命名空间可以嵌套，是的名称更短。</p>
    </div>
  );
};
